package routers

import (
	"net/http"
	"stacks/config"
	"stacks/controllers"
	"stacks/database"
	"stacks/middleware"

	"github.com/gin-gonic/gin"
)

// RegisterRoutes 注册路由
func RegisterRoutes(r *gin.Engine, cfg *config.Config) {
	// 创建控制器实例
	authController := controllers.NewAuthController(cfg)
	tenantController := controllers.NewTenantController()

	// 公开路由 - 无需认证
	api := r.Group("/api")
	{
		// 认证相关
		auth := api.Group("/auth")
		{
			auth.POST("/login", authController.Login)
			auth.POST("/register", authController.Register)
		}

		// 健康检查
		api.GET("/health", func(c *gin.Context) {
			// 获取数据库连接
			db := database.GetRawDB()
			if db == nil {
				c.JSON(http.StatusServiceUnavailable, gin.H{
					"status": "unhealthy",
					"error":  "Database not initialized",
				})
				return
			}

			// 检查数据库连接
			sqlDB, err := db.DB()
			if err != nil {
				c.JSON(http.StatusServiceUnavailable, gin.H{
					"status": "unhealthy",
					"error":  "Database connection failed",
				})
				return
			}

			if err := sqlDB.Ping(); err != nil {
				c.JSON(http.StatusServiceUnavailable, gin.H{
					"status": "unhealthy",
					"error":  "Database ping failed",
				})
				return
			}

			// 获取Redis连接
			rdb := database.GetRedis()
			if rdb == nil {
				c.JSON(http.StatusServiceUnavailable, gin.H{
					"status": "unhealthy",
					"error":  "Redis not initialized",
				})
				return
			}

			// 检查Redis连接
			if _, err := rdb.Ping(c.Request.Context()).Result(); err != nil {
				c.JSON(http.StatusServiceUnavailable, gin.H{
					"status": "unhealthy",
					"error":  "Redis connection failed",
				})
				return
			}

			c.JSON(http.StatusOK, gin.H{
				"status": "healthy",
			})
		})
	}

	// 租户管理 - 公开接口（实际项目中可能需要特殊权限）
	tenants := api.Group("/tenant")
	{
		tenants.GET("", tenantController.GetTenantList)
		tenants.GET("/:id", tenantController.GetTenantByID)
		tenants.POST("", tenantController.CreateTenant)
		tenants.PUT("/:id", tenantController.UpdateTenant)
		tenants.DELETE("/:id", tenantController.DeleteTenant)
	}

	// 受保护路由 - 需要认证
	protected := api.Group("/admin")
	protected.Use(middleware.JWTAuth(cfg))

	// 创建受保护路由管理器并注册所有路由
	protectedRoutes := NewProtectedRoutes(cfg)
	protectedRoutes.RegisterAll(protected)
}
